package com.changcheng.project.yuminsi.service.impl;

import com.alibaba.fastjson.JSON;

import com.changcheng.project.yuminsi.commons.RestTemplateCommons;
import com.changcheng.project.yuminsi.domain.CarDomain;
import com.changcheng.project.yuminsi.domain.OperInfoDomain;
import com.changcheng.project.yuminsi.mapper.CommonMapper;
import com.changcheng.project.yuminsi.domain.AcctInfoDomain;
import com.changcheng.project.yuminsi.error.BusinessException;
import com.changcheng.project.yuminsi.error.GlobalErrorCode;
import com.changcheng.project.yuminsi.service.AfterSaleService;
import com.changcheng.project.yuminsi.utils.GenerateSignUtil;
import com.changcheng.project.yuminsi.vo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yuminsi
 * @description
 * @date 2020/8/20 11:14
 * @since
 */
@SuppressWarnings("all")
@Service
public class AfterSaleServiceImpl implements AfterSaleService {

    private static final Logger logger = LoggerFactory.getLogger(AfterSaleServiceImpl.class);

    @Autowired
    private CommonMapper commonMapper;

    @Autowired
    private RestTemplateCommons restTemplate;

    @Autowired
    private HttpServletRequest request;

    private static String appkey = "9065275281";
    private static String secretkey = "2b673290caa2d9a82f1f7e845c80e4fe";

    /**
     * 15.ETC注销接口
     *
     * @param etcLogOffRequest
     * @return
     */
    @Override
    public BaseOutput etcLogOff(EtcLogOffRequest etcLogOffRequest) throws Exception {
        //已经登录放行
        String token = request.getHeader("token");
        OperInfoDomain operInfoDomain = commonMapper.queryOperInfoByToken(token);
        if (operInfoDomain == null) {
            throw new BusinessException(GlobalErrorCode.TOKEN_FAIL);
        }

        //手持机IMEI编号
        String IMEI = request.getHeader("IMEI");
        //签名
        String sign = request.getHeader("bt-auth-sign");
        //header
        String appkey = request.getHeader("bt-auth-appkey");
        String nonce = request.getHeader("bt-auth-nonce");
        String timestamp = request.getHeader("bt-auth-timestamp");

        //url
        String uri = request.getRequestURI();

        //参数
        //对象转json
        String etcLogOff = JSON.toJSONString(etcLogOffRequest);
        Map<String, Object> postBody = new HashMap<>();
        postBody.put("json", etcLogOff);
        String genSign = GenerateSignUtil.generateSignOfPost(uri, appkey, nonce, timestamp, postBody, secretkey);
        logger.info("POST生成的签名:  {}", genSign);

        //验证签名
       if (!genSign.equalsIgnoreCase(sign)) {
          throw new BusinessException(GlobalErrorCode.SIGN_FAIL);
        }

        String vin = etcLogOffRequest.getVin();
        Integer etcStatus = etcLogOffRequest.getEtcStatus();
        String username = request.getHeader("username");
        String acctId = etcLogOffRequest.getAcctId();

        //4.注销
        AcctInfoDomain acctInfoDomain = commonMapper.queryAcctInfoByAcctId(acctId);
        if (acctInfoDomain == null) {
            throw new BusinessException(GlobalErrorCode.ACCT_NOT_EXIST);
        }

//        acctInfoDomain.setStatus(EtcStatus.STATUS_8.getCode());
        acctInfoDomain.setAccerStatus(String.valueOf(etcLogOffRequest.getEtcStatus()));
        commonMapper.updateAcctInfoByAcctId(acctInfoDomain);
        commonMapper.deleteAcctInfoByAcctId(acctId);
        return BaseOutput.responseData(GlobalErrorCode.SUCCESS, null);
    }

    /**
     * 17.获取二次激活指令接口
     *
     * @param activInstructRequest
     * @return
     */
    @Override
    public BaseOutput getActivInstruct(String obuId, String random, String acctId) throws Exception {
        //已经登录放行
        String token = request.getHeader("token");
        OperInfoDomain operInfoDomain = commonMapper.queryOperInfoByToken(token);
        if (operInfoDomain == null) {
            throw new BusinessException(GlobalErrorCode.TOKEN_FAIL);
        }

        //手持机IMEI编号
        String IMEI = request.getHeader("IMEI");
        //签名
        String sign = request.getHeader("bt-auth-sign");
        //header
        String appkey = request.getHeader("bt-auth-appkey");
        String nonce = request.getHeader("bt-auth-nonce");
        String timestamp = request.getHeader("bt-auth-timestamp");

        //url
        String uri = request.getRequestURI();
        logger.info("路径:  {}", uri);

        //参数
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("obuId", obuId);
        parameters.put("random", random);
        parameters.put("acctId", acctId);

        String genSign = GenerateSignUtil.generateSignOfGet(uri, appkey, nonce, timestamp, parameters, secretkey);
        logger.info("Get生成的签名:  {}", genSign);

        //验证签名
       if (!genSign.equalsIgnoreCase(sign)) {
          throw new BusinessException(GlobalErrorCode.SIGN_FAIL);
        }

        AcctInfoDomain acctInfoDomain = commonMapper.queryAcctInfoByAcctId(acctId);
        if (acctInfoDomain == null) {
            throw new BusinessException(GlobalErrorCode.ACCT_NOT_EXIST);
        }

        //密钥体系（0聚利，1速通）
        Integer keySystem = 0;
        //1字节文件类型
        String fileType = "01";
        //4字节区域代码（北京）
        String areaCode = "B2E2CAD4";
        //文件偏移
        String offset = "26";
        //N字节要更新文件内容
        String fileData = "01";

        StringBuilder sb = new StringBuilder();
        sb.append("<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">\n");
        sb.append("<soap12:Body>\n");
        sb.append("<GM_ESAM_UPDATEFILE_CALMAC_ALL xmlns=\"http://tempuri.org/\">\n");
        sb.append("<nKeySystemType>" + keySystem + "</nKeySystemType>\n");
        sb.append("<strFileType>" + fileType + "</strFileType>\n");
        sb.append("<strAreaCodeNumber>" + areaCode + "</strAreaCodeNumber>\n");
        sb.append("<strEsamSerialNumber>" + obuId + "</strEsamSerialNumber>\n");
        sb.append("<strRandom>" + random + "</strRandom>\n");
        sb.append("<strFileData>" + fileData + "</strFileData>\n");
        sb.append("<nOffset>" + offset + "</nOffset>\n");
        sb.append("<RCos>" + "" + "</RCos>\n");
        sb.append("</GM_ESAM_UPDATEFILE_CALMAC_ALL>\n");
        sb.append("</soap12:Body>\n");
        sb.append("</soap12:Envelope>");
        logger.info("sb:{}", sb);

        //获取cos
        UniversalResponse universalResponse = new UniversalResponse();
        universalResponse.setApdu(restTemplate.getRcos(sb));
        return BaseOutput.responseData(GlobalErrorCode.SUCCESS, universalResponse);
    }

    /**
     * 18.激活结果同步
     *
     * @param activateNoticeRequest
     * @return
     */
    @Override
    public BaseOutput updateActiveStatus(ActivateResultRequest activateResultRequest) throws Exception {
        //已经登录放行
        String token = request.getHeader("token");
        OperInfoDomain operInfoDomain = commonMapper.queryOperInfoByToken(token);
        if (operInfoDomain == null) {
            throw new BusinessException(GlobalErrorCode.TOKEN_FAIL);
        }

        //手持机IMEI编号
        String IMEI = request.getHeader("IMEI");
        //操作人
        String username = request.getHeader("username");
        //签名
        String sign = request.getHeader("bt-auth-sign");
        //header
        String appkey = request.getHeader("bt-auth-appkey");
        String nonce = request.getHeader("bt-auth-nonce");
        String timestamp = request.getHeader("bt-auth-timestamp");

        //url
        String uri = request.getRequestURI();

        //参数
        //对象转json
        String activateResult = JSON.toJSONString(activateResultRequest);
        Map<String, Object> postBody = new HashMap<>();
        postBody.put("json", activateResult);
        String genSign = GenerateSignUtil.generateSignOfPost(uri, appkey, nonce, timestamp, postBody, secretkey);
        logger.info("POST生成的签名:  {}", genSign);

        //验证签名
       if (!genSign.equalsIgnoreCase(sign)) {
          throw new BusinessException(GlobalErrorCode.SIGN_FAIL);
        }

        String acctId = activateResultRequest.getAcctId();
        AcctInfoDomain acctInfoDomain = commonMapper.queryAcctInfoByAcctId(acctId);
        if (acctInfoDomain == null) {
            throw new BusinessException(GlobalErrorCode.ACCT_NOT_EXIST);
        }

        String status = activateResultRequest.getStatus();
        if ("0".equals(status)) {
            return BaseOutput.responseData(GlobalErrorCode.SUCCESS, null);
        }
        throw new BusinessException(GlobalErrorCode.FAIL);
    }


    /**
     * 通过VIN码获取车型编码/cc码
     * @param vin
     * @return
     */
    @Override
    public BaseOutput getVehiCcCode(String vin) throws Exception {
        //已经登录放行
        String token = request.getHeader("token");
        OperInfoDomain operInfoDomain = commonMapper.queryOperInfoByToken(token);
        if (operInfoDomain == null) {
            throw new BusinessException(GlobalErrorCode.TOKEN_FAIL);
        }

        //手持机IMEI编号
        String IMEI = request.getHeader("IMEI");
        //签名
        String sign = request.getHeader("bt-auth-sign");
        //header
        String appkey = request.getHeader("bt-auth-appkey");
        String nonce = request.getHeader("bt-auth-nonce");
        String timestamp = request.getHeader("bt-auth-timestamp");

        //url
        String uri = request.getRequestURI();
        logger.info("路径:  {}", uri);

        //参数
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("", "");


        String genSign = GenerateSignUtil.generateSignOfGet(uri, appkey, nonce, timestamp, parameters, secretkey);
        logger.info("Get生成的签名:  {}", genSign);

        //验证签名
        if (!genSign.equalsIgnoreCase(sign)) {
            throw new BusinessException(GlobalErrorCode.SIGN_FAIL);
        }

        AcctInfoDomain acctInfoDomain = commonMapper.queryAcctInfoByVin(vin);
        if (acctInfoDomain == null){
            throw new BusinessException(GlobalErrorCode.FAIL);
        }
        String vehicleModelCode = acctInfoDomain.getVehicleModelCode();
        String obuSupplier = acctInfoDomain.getObuSupplier();
        CcCodeResponse ccCodeResponse = new CcCodeResponse();
        ccCodeResponse.setVin(vin);
        ccCodeResponse.setVehicleModelCode(vehicleModelCode);
        ccCodeResponse.setObuSupplier(obuSupplier);
        return BaseOutput.responseData(GlobalErrorCode.SUCCESS, ccCodeResponse);
    }

}
